# 构建阶段
FROM node:22-slim AS builder

# 设置工作目录
WORKDIR /app

# 安装依赖构建工具
RUN apt-get update && \
    apt-get install -y python3 make g++ git && \
    rm -rf /var/lib/apt/lists/*

# 启用 corepack + 设置淘宝镜像（npm + pnpm）
RUN corepack enable && corepack prepare pnpm@10.8.0 --activate && \
    npm config set registry https://registry.npmmirror.com && \
    pnpm config set registry https://registry.npmmirror.com

# 拷贝 lock 文件和 package.json 优化缓存
COPY pnpm-lock.yaml ./
COPY package.json ./
COPY .npmrc ./

# 安装依赖
RUN pnpm install

# 拷贝项目源代码
COPY . .

# 构建生产版本
RUN pnpm build:prod

# 运行阶段
FROM node:22-slim AS runner

ENV NODE_ENV=production

WORKDIR /app

RUN corepack enable && corepack prepare pnpm@10.8.0 --activate && \
    pnpm config set registry https://registry.npmmirror.com

# 拷贝构建产物和依赖
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/package.json ./package.json
COPY --from=builder /app/pnpm-lock.yaml ./pnpm-lock.yaml
COPY --from=builder /app/node_modules ./node_modules

CMD ["pnpm", "start"]